package com.mark.springsecurity.controller;

import com.mark.springsecurity.domain.SysUser;
import com.mark.springsecurity.dto.req.SysUserCmd;
import com.mark.springsecurity.dto.req.SysUserQueryObj;
import com.mark.springsecurity.dto.resp.MessageType;
import com.mark.springsecurity.dto.resp.Msg;
import com.mark.springsecurity.dto.resp.SysUserDto;
import com.mark.springsecurity.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping()
    public ResponseEntity<Msg<Object>> save(@RequestBody @Validated SysUserCmd sysUserCmd) {
        userService.save(sysUserCmd.buildSysUser(sysUserCmd));
        Msg<Object> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, null);
        return new ResponseEntity<>(msg, HttpStatus.CREATED);
    }

    @GetMapping("/list")
    public ResponseEntity<Msg<Page<SysUserDto>>> list(SysUserQueryObj sysUserQueryObj, Pageable pageable) {
        Msg<Page<SysUserDto>> pageMsg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, SysUserDto.buildListWithPage(sysUsers(sysUserQueryObj, pageable)));
        return new ResponseEntity<>(pageMsg, HttpStatus.OK);
    }

    private Page<SysUser> sysUsers(SysUserQueryObj sysUserQueryObj, Pageable pageable) {
        return userService.findAll(SysUserQueryObj.buildExample(sysUserQueryObj), pageable);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Msg<SysUserDto>> getOne(@PathVariable Long id) {
        Msg<SysUserDto> msg =
                new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, SysUserDto.build(userService.getOne(id)));
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Msg<Object>> update(
            @PathVariable Long id, @RequestBody SysUserCmd sysUserCmd) {
        userService.update(SysUserCmd.buildSysUser(id, sysUserCmd));
        Msg<Object> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, null);
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Msg<Object>> delete(@PathVariable Long id) {
        userService.delete(id);
        Msg<Object> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, null);
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }
}
